package com.lgywin.userserver.server;


import com.lgywin.userserver.comm.Cache;
import com.lgywin.userserver.dao.GameServerMapper;
import com.lgywin.userserver.entity.GameServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Set;

@Component
@Slf4j
public class NettyClient implements CommandLineRunner {
    @Autowired
    private GameServerMapper gameServerDao;

    public void start() throws Exception{
        log.info("start ===========================");
        RestTemplate restTemplate = new RestTemplate();
        while(true){
            Thread.sleep(3000);

            if(Cache.GameServerMap.size() == 0){
                List<GameServer> list = gameServerDao.all();
                for (int i = 0; i < list.size(); i++) {
                    GameServer bean = list.get(i);
                    Cache.GameServerMap.put(bean.getId(),bean);
                }
            }

            Set<Integer> idSet = Cache.GameServerMap.keySet();
            for (int i : idSet) {
                GameServer bean = Cache.GameServerMap.get(i);

                String url = "http://"+bean.getIp()+":"+bean.getPort_http()+"/serverState";
                try {
                    GameServer forObject = restTemplate.getForObject(url,GameServer.class);
                    log.info(forObject.getIp()+" "+forObject.getPort_http()+" -----------forObject="+forObject.getName()+" "+forObject.getAddress());
                }catch (Exception e){
                    log.info(bean.getName()+" ["+bean.getAddress()+ "] " +url+" 服务器没开");
                }
            }


        }
    }

    @PreDestroy
    public void destroy() {

    }

    @Async//注意这里，组件启动时会执行run，这个注解是让线程异步执行，这样不影响主线程
    @Override
    public void run(String... args) throws Exception {
        start();
    }
}